package app.controllers.api;

import app.Const;
import app.constant.OrderConstant;
import app.constant.ProductConstant;
import app.constant.TransferConstant;
import app.dtos.ProductDto;
import app.kit.VerifyKit;
import app.models.app.ProductDetails;
import app.models.member.BankCard;
import app.models.member.Member;
import app.models.member.MemberProduct;
import app.models.order.Order;
import app.models.product.Details;
import app.models.product.Product;
import app.models.product.ProductYields;
import app.models.transfer.TransferProduct;
import app.services.OrderService;
import app.services.auth.AuthInterceptor;
import app.services.auth.AuthParam;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.google.common.primitives.Doubles;
import com.google.common.primitives.Floats;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.JsonKit;
import goja.GojaConfig;
import goja.date.DateFormatter;
import goja.kits.ArithKit;
import goja.lang.Lang;
import goja.mvc.Controller;
import goja.mvc.interceptor.PUT;
import org.joda.time.DateTime;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * The url product Controller.
 * </p>
 *
 * @author sagyf yang
 * @version 1.0
 * @since JDK 1.6
 */
public class ProductController extends Controller {

    public static final String TRANSFER_PARAM = "transfer";

    /**
     * The index route.
     * the url /product
     */
    @Before(GET.class)
    public void index() {
        int product_id = getParaToInt();
        if (product_id > 0) {
            final Product product = Product.dao.findByAllInfo(product_id);
            if (Lang.isEmpty(product)) {
                renderAjaxFailure("产品数据不存在，无法查找");
                return;
            }
            List<ProductDetails> details = ProductDetails.dao.findbyProduct(product_id);

            renderAjaxSuccess(ProductDto.build(product, details));
        } else {
            renderAjaxFailure("产品ID非法");
        }
    }





    /**
     * 产品购买
     */
    @Before({POST.class, AuthInterceptor.class})
    @AuthParam(auth = true)
    public void purchase() {
        // 取得当前登录会员
        Member member = getAttr(AuthInterceptor.ATTR_MEMBER);

        int product_id = getParaToInt(Const.FIELD_PRODUCT);
        if (product_id <= 0) {
            renderAjaxFailure("请选择购买投资产品");
            return;
        }
        Order order;

        int valuedate_offset;
        boolean transfer = getParaToBoolean(TRANSFER_PARAM, false);

        if (transfer) {
            //  转让产品交易
            TransferProduct transferProduct = TransferProduct.dao.findByInfo(product_id);
            if (transferProduct == null) {
                renderAjaxFailure("请选择转让产品");
                return;
            }
            if (transferProduct.getNumber(Const.FIELD_STATUS).intValue() != TransferConstant.STATUE_TRADING) {
                renderAjaxFailure("转让产品已经完成交易，无法再次交易");
                return;
            }

            order = OrderService.me.createTfrOrder(member.getId(), transferProduct);

            order.save();

            valuedate_offset = transferProduct.getNumber(Const.FIELD_VALUEDATEOFFSET).intValue();

        } else {
            Product product = Product.dao.findById(product_id);
            if (product == null) {
                renderAjaxFailure("请选择购买投资产品");
                return;
            }
            if (product.getNumber(Const.FIELD_STATUS).intValue() != ProductConstant.ONLINE) {
                renderAjaxFailure("产品不在上架状态无法交易");
                return;
            }

            order = OrderService.me.createBuyOrder(member, product);
            valuedate_offset = product.getNumber(Const.FIELD_VALUEDATEOFFSET).intValue();
        }

        DateTime now = DateTime.now();
        now = now.plusDays(valuedate_offset);

        Map<String, Object> result = Maps.newHashMap();
        result.put("order", order);
        result.put("time", now.toString(DateFormatter.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM));

        renderAjaxSuccess(result);


    }

    /**
     * 确定购买接口
     */
    @Before({POST.class, AuthInterceptor.class})
    @AuthParam(auth = true)
    public void confirm() {

        int order_id = getParaToInt();
        if (order_id <= 0) {
            renderAjaxError("无法完成请求!");
            return;
        }

        //  投资金额
        String amount_str = getPara(Const.FIELD_AMOUNT);
        if (Strings.isNullOrEmpty(amount_str) || !VerifyKit.checkDecimals(amount_str)) {
            renderAjaxFailure("请输入正确的金额!");
            return;
        }
        final Double amount = Doubles.tryParse(amount_str);
        if (amount == null) {
            renderAjaxFailure("请输入正确的金额!");
            return;
        }
        // 银行卡
        int bank_card_id = getParaToInt("bankcard");
        if (bank_card_id <= 0) {
            renderAjaxFailure("请选择银行卡支付");
            return;
        }
        Optional<MemberProduct> purchase;

        BankCard bankCard = BankCard.dao.findById(bank_card_id);
        if (bankCard == null) {
            renderAjaxFailure("未绑定的银行卡");
            return;
        }

        Order order = Order.dao.findById(order_id);
        if(order.getNumber(Const.FIELD_STATUS).intValue() == OrderConstant.TRADE_SUCCESS){
            renderAjaxFailure("该订单已经确定，无法重复进行");
            return;
        }
        Member member = getAttr(AuthInterceptor.ATTR_MEMBER);

        boolean transfer = getParaToBoolean(TRANSFER_PARAM, false);

        if(transfer){

            purchase = OrderService.me.confirm(order, bankCard, amount, member);
        } else {


            // TODO 与银行接口交互,需要检验银行卡余额

            purchase = OrderService.me.confirm(order, bankCard, amount, member);
        }



        if (purchase.isPresent()) {
            JsonKit.setDatePattern(DateFormatter.YYYY_MM_DD_HH_MM_SS);
            renderAjaxSuccess(purchase.get());
        } else {
            renderAjaxFailure("购买失败");
        }
    }

    /**
     * HTML5 展示产品详情
     */
    @Before(GET.class)
    public void intro() {

        List<Details> detailses = Details.dao.findByAppItem(getParaToInt());
        setAttr("details", detailses);

        setAttr("image_domain", GojaConfig.getProperty("image.domain"));

        render("/intro.ftl");
    }


    @Before(PUT.class)
    public void yield() {
        int product_id = getParaToInt();
        final String yield_str = getPara(Const.FIELD_YIELD);
        if (Strings.isNullOrEmpty(yield_str) || !VerifyKit.checkDecimals(yield_str)) {
            renderAjaxFailure("请输入正确的利率");
            return;
        }
        Float yield = Floats.tryParse(yield_str);
        if (yield == null || yield > 100 || yield < 1) {
            renderAjaxFailure("收益率只能在百分之1到100之前");
            return;
        }
        if (product_id > 0) {
            ProductYields productYields = new ProductYields();
            productYields.set(Const.FIELD_PRODUCT, product_id);

            productYields.set(Const.FIELD_YIELD, ArithKit.div(yield, 100, 4));
            productYields.set("update_time", DateTime.now().toDate());
            productYields.set("init_flag", false);
            if (productYields.save()) {
                renderAjaxSuccess();
            } else {
                renderAjaxError("更新收益率失败");
            }
        }
    }
}